package org.jeecg.modules.demo.mes.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.demo.mes.entity.MesWorkOrder;
import org.jeecg.modules.demo.mes.entity.MesWorkOrderDetail;
import org.jeecg.modules.demo.mes.mapper.MesWorkOrderMapper;
import org.jeecg.modules.demo.mes.service.IMesWorkOrderDetailService;
import org.jeecg.modules.demo.mes.service.IMesWorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 工单表
 * @Author: jeecg-boot
 * @Date:   2022-11-02
 * @Version: V1.0
 */
@Service
public class MesWorkOrderServiceImpl extends ServiceImpl<MesWorkOrderMapper, MesWorkOrder> implements IMesWorkOrderService {

    @Autowired
    private IMesWorkOrderDetailService mesWorkOrderDetailService;

    /**
     * 通用工单表单表查询
     * @param cxMap 查询map
     * @return 。。
     * @throws JeecgBootException
     */
    @Override
    public List<MesWorkOrder> queryTechnologyListSelective(Map<String, Object> cxMap) throws JeecgBootException {
        if (cxMap==null){
            return new ArrayList<>();
        }
        return this.baseMapper.queryTechnologyListSelective(cxMap);
    }

    /**
     * 下发
     * @param id 工单id
     * @param workOrderStatus 工单状态
     * @throws JeecgBootException
     */
    @Override
    @Transactional(readOnly = false,isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
    public void grant(String id, String workOrderStatus) throws JeecgBootException {
        if (StringUtils.isBlank(id)){
            throw new JeecgBootException("唯一id不能为空");
        }
        if (StringUtils.isBlank(workOrderStatus)){
            throw new JeecgBootException("工单状态不能为空");
        }
        //如果是下发，需要校验该产线是否存在另外一条是下发状态的
        if (StringUtils.equals(workOrderStatus,"2")){
            final MesWorkOrder mesWorkOrder = this.getById(id);
            final Map<String,Object> cxMap = new HashMap<>();
            cxMap.put("factoryId",mesWorkOrder.getFactoryId());
            cxMap.put("workshopId",mesWorkOrder.getWorkshopId());
            cxMap.put("lineId",mesWorkOrder.getLineId());
            final List<MesWorkOrder> mesWorkOrders = this.queryTechnologyListSelective(cxMap);
            if (mesWorkOrders!=null && mesWorkOrders.size()>1){
                for (MesWorkOrder temp : mesWorkOrders) {
                    if (
                            !StringUtils.equals(temp.getId(),id)  //不是当前工单
                            && StringUtils.equals("2",temp.getWorkOrderStatus()) // 该工单是下发状态
                            && StringUtils.equals("1",temp.getFinishStatus()) //该工单是未完成状态
                    ){
                        throw new JeecgBootException("该产线已经有下发状态的订单了，请先将该订单冻结，再操作本订单");
                    }
                }
            }
        }
        this.baseMapper.grant(id,workOrderStatus);
    }

    @Override
    @Transactional(readOnly = false,isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
    public void saveWorkOrder(MesWorkOrder mesWorkOrder) throws JeecgBootException {
        String mesWorkOrderId = mesWorkOrder.getId();
        if (StringUtils.isBlank(mesWorkOrderId)) {
            this.save(mesWorkOrder);
            mesWorkOrderId = mesWorkOrder.getId();
        }else {
            this.updateById(mesWorkOrder);
        }
        final Integer quantity = mesWorkOrder.getQuantity();
        if (quantity<0){
            throw new JeecgBootException("工单数量必须是正整数");
        }
        //查询详细表
        final Map<String,Object> cxMap = new HashMap<>();
        cxMap.put("workOrderId",mesWorkOrderId);
        //由于下发之后就不允许编辑了，所以不用考虑用户填完之后又修改数量的情况了
        final List<MesWorkOrderDetail> detailList =  mesWorkOrderDetailService.queryMesWorkOrderDetailListSelective(cxMap);
        if (detailList!=null && detailList.size()!=0){
            //先将旧的删掉
            final List<String> ids = detailList.stream().map(MesWorkOrderDetail::getId).collect(Collectors.toList());
            mesWorkOrderDetailService.removeByIds(ids);
        }
        final String workOrderNumber = mesWorkOrder.getWorkOrderNumber();
        final String userName = JwtUtil.getUserName();
        final Date now = new Date();
        for (int i = 0; i < quantity; i++) {
            final MesWorkOrderDetail workOrderDetail = new MesWorkOrderDetail();
            workOrderDetail.setCreateBy(userName);
            workOrderDetail.setCreateTime(now);
            workOrderDetail.setFinishStatus("1");
            workOrderDetail.setUpdateBy(userName);
            workOrderDetail.setUpdateTime(now);
            workOrderDetail.setWorkOrderId(mesWorkOrderId);
            workOrderDetail.setWorkOrderBarCode(workOrderNumber+String.format("%05d",i));
            mesWorkOrderDetailService.save(workOrderDetail);
        }
    }

    @Override
    @Transactional(readOnly = false,isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
    public void removeWorkOrderById(String id) throws JeecgBootException {
        //由于下发之后就不允许删除了，所以不用校验其他的
        this.removeById(id);
        final Map<String,Object> cxMap = new HashMap<>();
        cxMap.put("workOrderId",id);
        final List<MesWorkOrderDetail> detailList =  mesWorkOrderDetailService.queryMesWorkOrderDetailListSelective(cxMap);
        final List<String> ids = detailList.stream().map(MesWorkOrderDetail::getId).collect(Collectors.toList());
        mesWorkOrderDetailService.removeByIds(ids);
    }
}
